package pqsk.android.audio.Models;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.Socket;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Vector;

public class BroadcasterService extends Thread
{
    private BufferedReader reader = null;
    private BufferedWriter writer = null;
    private static Vector<BroadcasterService> handlers = new Vector<BroadcasterService>( 10 );

    public BroadcasterService(Socket socket)
    {
        //this.connection = connection;
        try
        {
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        }
        catch(IOException ex)
        {
            System.out.println("Serice message: " + ex.getMessage());
        }
    }
    @Override
    public void run()
    {
        String line;
        synchronized(handlers)
        {
            handlers.addElement(this);
        }
        try
        {
            while(true)
            {
                line = reader.readLine();
                for(int i = 0; i < handlers.size(); i++)
                {
                        synchronized(handlers)
                        {
                        	BroadcasterService handler =
                                (BroadcasterService)handlers.elementAt(i);
                            handler.writer.write(line + "\n");
                            handler.writer.flush();
                        }
                }
                System.out.println("Service message: " + line);
                //service();
            }
        }
        catch(IOException ex)
        {
            System.out.println("Service message: " + ex.getMessage());
        }
        finally
        {
            synchronized(handlers)
            {
                handlers.removeElement(this);
            }
            try
            {
                reader.close();
                writer.close();
            }
            catch(IOException ex)
            {
                System.out.println("Service message: " + ex.getMessage());
            }


        }
    } // end method run

}

